package dispatcher.gui.event;

import java.util.concurrent.ConcurrentLinkedQueue;

import dispatcher.gui.state.GroupDispatcherStateHandler;
import dispatcher.gui.state.StateHandler;
import state.Globals;
import state.group.events.BaseEvent;
import state.group.events.EventCollection;

/**
 * This class will talk attempt to update the local state of the GUI from messages
 * received from the group dispatcher
 * @author Caleb
 *
 */
public class StatusUpdateThread extends Thread {

	private boolean isRunning;
	
	private ConcurrentLinkedQueue<EventCollection> queueEvents;
	/**
	 * The main constructor
	 * @param events The main events received from group dispatcher 
	 */
	public StatusUpdateThread(){
		super("StatusUpdateThread");
		queueEvents = new ConcurrentLinkedQueue<EventCollection>();
		this.isRunning = true;
	}
	
	@Override
	public void run(){
		synchronized(this){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		while(isRunning){
			Globals.getLogger().log("Update Event", this.getClass().getName(), "run");
			
			StateHandler handler = GroupDispatcherStateHandler.getInstance();
			// Attempts to update events
			handler.updateEvents(this.queueEvents.poll());
			synchronized(this){
				try {
					if(this.queueEvents.size() <= 0){
						this.wait();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public synchronized void setEvents(EventCollection events){
		this.queueEvents.add(events);
		System.out.println("Events Added");
		for(BaseEvent e : events){
			System.out.println("Event is : " + e.getEventType());
		}
	}
	
	public synchronized void terminate(){
		isRunning = false;
		this.queueEvents.clear();
	}
}
